<template>
	<up-upload :accept="accept" width="148rpx" height="148rpx" :fileList="fileList" @afterRead="afterRead" @delete="deleteFile" multiple :maxCount="limit"></up-upload>
</template>

<script setup>
import apis from '@/apis'
import axios from '@/apis/request'
import { ref, watch } from 'vue'
import FormData from 'miniprogram-formdata'

const props = defineProps({
	modelValue: {
		type: [Array, String],
		default(rawProps) {
			return rawProps.multiple ? [] : ''
		}
	},
	accept: {
		type: String,
		default: 'media'
		// ,.mp4,.avi,.mov视频文件
	},
	multiple: {
		type: Boolean,
		default: true
	},
	limit: {
		type: Number,
		default: 6
	},
	maxSize: {
		type: Number,
		default: 50
	},
	readonly: {
		type: Boolean,
		default: false
	}
})

const fileList = ref([])
watch(
	() => props.modelValue,
	val => {
		fileList.value = val.map(item => {
			return { url: item.filePrefix + item.fileUrl }
		})
	},
	{
		immediate: true
	}
)

function afterRead(event) {
	const files = event.file
	let fileListLen = fileList.value.length
	files.forEach(item => {
		fileList.value.push({
			...item,
			status: 'uploading',
			message: '上传中'
		})
	})
	files.forEach(item => {
		const formData = new FormData()
		formData.append('file', item.url)
		axios
			.post(apis.common.upload, formData)
			.then(res => {
				let item = fileList.value[fileListLen]
				fileList.value.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: res.filePrefix + res.fileUrl
				})
				fileListLen++
			})
			.catch(() => {
				fileList.value.splice(fileListLen, 1)
			})
	})
}

function deleteFile(event) {
	fileList.value.splice(event.index, 1)
}
</script>

<style scoped lang="scss"></style>
